
////JQUERY JSON LIBRARY:
			/*
			* This document is licensed as free software under the terms of the
			* MIT License: <a href="http://www.opensource.org/licenses/mit-license.php" title="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>
			*
			* Adapted by Rahul Singla.
			*
			* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org 
			* website's <a href="http://www.json.org/json2.js" title="http://www.json.org/json2.js">http://www.json.org/json2.js</a>, which proclaims:
			* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
			* I uphold.
			*
			* It is also influenced heavily by MochiKit's serializeJSON, which is 
			* copyrighted 2005 by Bob Ippolito.
			*/

			/**
			* jQuery.JSON.encode( json-serializble ) Converts the given argument into a
			* JSON respresentation.
			* 
			* If an object has a "toJSON" function, that will be used to get the
			* representation. Non-integer/string keys are skipped in the object, as are
			* keys that point to a function.
			* 
			* json-serializble: The *thing* to be converted.
			*/
jQuery.JSON = {
				encode: function(o) {
					if (typeof (JSON) == 'object' && JSON.stringify)
						return JSON.stringify(o);

					var type = typeof (o);

					if (o === null)
						return "null";

					if (type == "undefined")
						return undefined;

					if (type == "number" || type == "boolean")
						return o + "";

					if (type == "string")
						return this.quoteString(o);

					if (type == 'object') {
						if (typeof o.toJSON == "function")
							return this.encode(o.toJSON());

						if (o.constructor === Date) {
							var month = o.getUTCMonth() + 1;
							if (month < 10)
								month = '0' + month;

							var day = o.getUTCDate();
							if (day < 10)
								day = '0' + day;

							var year = o.getUTCFullYear();

							var hours = o.getUTCHours();
							if (hours < 10)
								hours = '0' + hours;

							var minutes = o.getUTCMinutes();
							if (minutes < 10)
								minutes = '0' + minutes;

							var seconds = o.getUTCSeconds();
							if (seconds < 10)
								seconds = '0' + seconds;

							var milli = o.getUTCMilliseconds();
							if (milli < 100)
								milli = '0' + milli;
							if (milli < 10)
								milli = '0' + milli;

							return '"' + year + '-' + month + '-' + day + 'T' + hours + ':'
						+ minutes + ':' + seconds + '.' + milli + 'Z"';
						}

						if (o.constructor === Array) {
							var ret = [];
							for (var i = 0; i < o.length; i++)
								ret.push(this.encode(o[i]) || "null");

							return "[" + ret.join(",") + "]";
						}

						var pairs = [];
						for (var k in o) {
							var name;
							var type = typeof k;

							if (type == "number")
								name = '"' + k + '"';
							else if (type == "string")
								name = this.quoteString(k);
							else
								continue; // skip non-string or number keys

							if (typeof o[k] == "function")
								continue; // skip pairs where the value is a function.

							var val = this.encode(o[k]);

							pairs.push(name + ":" + val);
						}

						return "{" + pairs.join(", ") + "}";
					}
				},

				/**
				* jQuery.JSON.decode(src) Evaluates a given piece of json source.
				*/
				decode: function(src) {
					if (typeof (JSON) == 'object' && JSON.parse)
						return JSON.parse(src);
					return eval("(" + src + ")");
				},

				/**
				* jQuery.JSON.decodeSecure(src) Evals JSON in a way that is *more* secure.
				*/
				decodeSecure: function(src) {
					if (typeof (JSON) == 'object' && JSON.parse)
						return JSON.parse(src);

					var filtered = src;
					filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
					filtered = filtered
				.replace(
						/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
						']');
					filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

					if (/^[\],:{}\s]*$/.test(filtered))
						return eval("(" + src + ")");
					else
						throw new SyntaxError("Error parsing JSON, source is not valid.");
				},

				/**
				* jQuery.JSON.quoteString(string) Returns a string-repr of a string, escaping
				* quotes intelligently. Mostly a support function for JSON.encode.
				* 
				* Examples: >>> jQuery.JSON.quoteString("apple") "apple"
				* 
				* >>> jQuery.JSON.quoteString('"Where are we going?", she asked.') "\"Where
				* are we going?\", she asked."
				*/
				quoteString: function(string) {
					if (string.match(this._escapeable)) {
						return '"' + string.replace(this._escapeable, function(a) {
							var c = this._meta[a];
							if (typeof c === 'string')
								return c;
							c = a.charCodeAt();
							return '\\u00' + Math.floor(c / 16).toString(16)
						+ (c % 16).toString(16);
						}) + '"';
					}
					return '"' + string + '"';
				},

				_escapeable: /["\\\x00-\x1f\x7f-\x9f]/g,

				_meta: {
					'\b': '\\b',
					'\t': '\\t',
					'\n': '\\n',
					'\f': '\\f',
					'\r': '\\r',
					'"': '\\"',
					'\\': '\\\\'
				}
			}

/*
 * FUNCTIONS By 15 Green leaves
 * 
 */


var meta_marker='_value';
var apm_show_attributes=false;
var filters={};



function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

var fgl_setAutoSetSaveTitle=function(obj){
	form=jQuery('#post');
	var ob=obj
	jQuery('#post').attr('obj',obj);
	jQuery('#post').live('submit',function(){
			//alert(jQuery(this).attr('obj'));
			
			///SEt POST TITLE FROM OTHER FIELDS FOLLOWING SCHEMA
			postTitleObj=jQuery('input[name="post_title"]');
			var str=ob.schema;
			 jQuery.each(ob.fields,function(index, field) {
		  		//alert(index + ': ' + field.field+ ': ' + field.field_type); 
		  		fi=jQuery('input[name="'+field.field+meta_marker+'"]');
		  		if(field.field_type!=='select'){
		  			str=str.split('{'+field.field+'}').join(jQuery(fi).val());
		  		} else {
		  			o=jQuery('#'+field.field);
		  			v=jQuery(o).find('option:selected').text();
		  			str=str.split('{'+field.field+'}').join(v);
		  		}
			 })
			 D=new Date();
		  	str=str.split('[currentdate]').join(D.getFullYear()+"-"+D.getMonth()+"-"+D.getDate());
			jQuery(postTitleObj).val(str);
			
			//CHECK REQUIRED
			var test=true;
			fi=jQuery('input[class="apm_is_required"]');
			 jQuery.each(fi,function(index, field) {
			 	if(jQuery(field).val()==""){
			 		test=false;
	                		jQuery(field).parent().parent().addClass('apm_invalid');
			 	}
			 });
			 
			 //CHECK EMAIL
			fi=jQuery('input[class="apm_is_email"]');
			 jQuery.each(fi,function(index, field) {
			 	 var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 				  var address = jQuery(field).val();
  				 if(reg.test(address) == false && address!=='') {
	                		jQuery(field).parent().parent().addClass('apm_invalid');
			 		test=false;
		                }
			 });
			 
			 //CHECK NUMBERS
			fi=jQuery('input[class="apm_is_numbers"]');
			 jQuery.each(fi,function(index, field) {
			 	  var num = jQuery(field).val();
				if ( isNaN(num)) {
					jQuery(field).parent().parent().addClass('apm_invalid');
		 			test=false;
		                } 
			 });
			 
			 
			 //CHECK PHONE
			fi=jQuery('input[class="apm_is_phone"]');
			 jQuery.each(fi,function(index, field) {
			 	  var phone = jQuery(field).val();
		               var stripped = phone.replace(/[\(\)\.\-\+\ ]/g, '');    
				 if (isNaN(stripped)) {
					jQuery(field).parent().parent().addClass('apm_invalid');
		 			test=false;
				    } else if (stripped.length <8 && stripped.length >0 ) {
					jQuery(field).parent().parent().addClass('apm_invalid');
		 			test=false;
				    } 
			 });
			 
			 if(test==false){
			 	alert("Some fields are invalid.")
			 	return false;
			 }
			
	});
	
}
var fgl_setAutoSetTitle=function(obj){
	var inputs=jQuery(':input');
	//alert(posttitle);
	var myobj=obj;
	var postTitleObj=null;
	postTitleObj=jQuery('input[name="post_title"]');
	var str=obj.schema;
	 jQuery.each(obj.fields,function(index, field) {
  		//alert(index + ': ' + field.field+ ': ' + field.field_type); 
  		fi=jQuery('input[name="'+field.field+meta_marker+'"]');
  		if(field.field_type!=='select'){
  			str=str.split('{'+field.field+'}').join(jQuery(fi).val());
  		} else {
  			o=jQuery('#'+field.field);
  			v=jQuery(o).find('option:selected').text();
  			str=str.split('{'+field.field+'}').join(v);
  		}
	 })
	 D=new Date();
  	str=str.split('[currentdate]').join(D.getFullYear()+"-"+D.getMonth()+"-"+D.getDate());
	jQuery(postTitleObj).val(str);
	return;
}

var fgl_deleteComment=function(id,fieldname){
	var commentTpl=jQuery("#apm_comment_"+id);
	var commentNb=jQuery("#"+fieldname+"_comment_nb");
	
	nb=Number(jQuery(commentNb).html())-1;
	jQuery(commentNb).html(nb);
	
	commentTpl.animate({
		opacity:0
	},500, function() {
    		commentTpl.hide();
  })
  	jQuery.ajax({
	  url: ajaxurl ,
 	 type: "POST",
 	 data: "comment_id="+id+"&action=apm_delete_comments",
	  //context: document.body,
	  success: function(data){
		
	  }
	});
	
}

var apm_convert=function(o,action,post_id,appname,post_type){
	document.location.href="admin.php?page="+appname+"-main-menu&post_id="+post_id+"&action_name="+action+"&post-type="+post_type+"&action-type=convert";
	
}

var apm_actionbtn=function(o,action,post_id,appname,post_type){
	var fields=jQuery(o).attr('fields');
	oFields=eval(fields);
	  jQuery.each(oFields, function(key,field){  
	  	fieldToUpdate=jQuery('input[name="'+field[0]+meta_marker+'"]');
	  	if(jQuery(fieldToUpdate).val()==undefined){
	  		if(document.post[field[0]+meta_marker]!==undefined){//= is select
		  		o=document.post[field[0]+meta_marker].options[0];
		  		//document.post[field[0]+meta_marker].selectedIndex =5;
		  		for (var i = 0; i < document.post[field[0]+meta_marker].length; i++) 
				{
					if (Number(document.post[field[0]+meta_marker].options[i].value) == Number(field[1]))
					{
						//alert(document.post[field[0]+meta_marker].options[i].value +'-'+ field[1]);
						document.post[field[0]+meta_marker].selectedIndex =i;
						//document.post[field[0]+meta_marker].selected = true;
				        }
				}
			}
			if(tinyMCE.get(field[0]+meta_marker+'_comment')!==undefined){
				txt=tinyMCE.get(field[0]+meta_marker+'_comment').getContent();//jQuery(commentBlock).attr("value");
				//tinyMCE.get('content id').getContent()
				tinyMCE.get(field[0]+meta_marker+'_comment').setContent(field[1]);
			}
	  		//jQuery(fieldToUpdate).val("3");
  		} else {
  			val=field[1];
  			if(val=='NOW()'){
  				var myDate=new Date();
  				m=myDate.getMonth();
  				m++;
  				if(m<10){
  					m='0'+m;
  				}
  				d=myDate.getDate();
  				if(d<10){
  					d='0'+d;
  				}
				val=m+"/"+d+"/"+myDate.getFullYear();
  			}
  			if(val=='TIME()'){
  				var myDate=new Date();
  				h=myDate.getHours();
  				m=myDate.getMinutes();
  				if(m<10){
  					m='0'+m;
  				}
  				if(h<10){
  					d='0'+h;
  				}
				val=h+":"+m;
  			}
  			jQuery(fieldToUpdate).val(val);
  		}
	  	
	  });
	  jQuery("#post").submit();
	//document.location.href="admin.php?page="+appname+"-main-menu&post_id="+post_id+"&action_name="+action+"&post-type="+post_type+"&action-type=convert";
	
}

var apm_add_notif=function(o){
	var userList=jQuery(o).prev();
	var notifField=jQuery(o).next();
	//alert(userList.val());
	if(notifField.val().indexOf(',')>-1){
		var notifUsersList=notifField.val().split(',');
	} else if(notifField.val()!==""){
		var notifUsersList=[notifField.val()];
	}
	var userToAdd=userList.val();


	var newNotifUsersList=[];
	var already_exist=false;
	if(notifField.val()!==""){
		  jQuery.each(notifUsersList, function(key,userid){  
		  	if(Number(userid)!==Number(userToAdd) && Number(userid)!==0){
		  		newNotifUsersList.push(userid);
		  	} else {
		  		already_exist=true;
		  	}
		});
	}
	newNotifUsersList.push(userToAdd);
	//alert(jQuery(o).next().next().html());
	if(already_exist==false){
		newUserStr="<span class='apm_user_listed'>"+jQuery(o).prev().find("option:selected").text()+" <div><img src='"+apm_settings.paths.img+"/delete_16.png'' onclick='apm_remove_notif(this,"+userToAdd+ ");' style='cursor:pointer;' fieldname='"+jQuery(o).attr('fieldname')+"'/></div></span>";
		jQuery(o).prev().prev().prev().prev().append(newUserStr);
	}
	//
	notifField.val(newNotifUsersList.join(','));
	
}

var apm_remove_notif=function(o,id){
	jQuery(o).parent().parent().hide();
 	field=jQuery('#'+jQuery(o).attr('fieldname')+'_apm');
 	var idToRemove=id;
 	
	
		
	if(field.val().indexOf(',')>-1){
		var notifUsersList=field.val().split(',');
		newNotifUsersList=[];
		  jQuery.each(notifUsersList, function(key,userid){  
		  	if(Number(userid)!==Number(idToRemove) ){
		  		newNotifUsersList.push(userid);
		  	} 
		});
		field.val(newNotifUsersList.join(','));
	} else {
		//alert(field.val());
		field.val('');
	}
	
	
		//alert(newNotifUsersList);
 	//alert(field+"/"+jQuery(field).val());
}

var flg_comments_list=[];
var fgl_add_to_comments_list=function(id,fieldname,post_id){
	flg_comments_list.push({
		id:id,
		fieldname:fieldname,
		post_id:post_id
	});
}

var center_layer=function(obj){
	w=obj.width();
	h=obj.height();
	obj.css('left',((jQuery(window).width()-w)/2)+"px");
	s=jQuery(window).scrollTop() ;
	winh=jQuery(window).height();
	obj.css('top',((winh-h)/2+s)+"px");
}

 var apm_show_categ_add=function(obj){

 	div=jQuery("#apm_categ_layer");
 	tagcateg=jQuery("#tag-categ");
 	jQuery(tagcateg).attr('value',jQuery(obj).attr('category_name'));
 	//alert();
 	
 	center_layer(div); 
 	div.show();
 	name=jQuery("#tag-name");
 	name.focus();
 }
 
 var fgl_addCategory=function(obj){
 	div=jQuery("#apm_categ_layer");
 	name=jQuery("#tag-name");
 	slug=jQuery("#tag-slug");
 	tagcateg=jQuery("#tag-categ");
 	description=jQuery("#tag-description");
 	layer_sending=jQuery("#apm_categ_layer_sending");
 	layer_button=jQuery("#apm_categ_layer_button");
 	alertdiv=jQuery("#apm_categ_layer_alert");
 	categname=jQuery(tagcateg).val();
 	checklist=jQuery("#"+categname+"checklist");
 	if(jQuery(name).val()==''){
 		alertdiv.show();
 		name.focus();
	} else {
 		alertdiv.hide();
 		layer_button.hide();
 		layer_sending.show();
 		jQuery.ajax({
			  url: ajaxurl ,
		 	 type: "POST",
		 	 data: "name="+jQuery(name).val()+"&slug="+jQuery(slug).val()+"&description="+jQuery(description).val()+"&tagcateg="+jQuery(tagcateg).val()+"&action=apm_add_category",
			  //context: document.body,
			  success: function(data){
				dataStr=String(data);
				dataStr=dataStr.substring(0,dataStr.length-1);
				dataStr=Number(dataStr);
 				checklist.append('<li id="'+categname+'-'+dataStr+'"><label class="selectit"><input value="'+dataStr+'" name="tax_input['+categname+'][]" id="in-'+categname+'-'+dataStr+'" type="checkbox"> '+jQuery(name).val()+'</label></li>');
 				layer_sending.hide();
 				layer_button.show();
 				jQuery(name).val('');
 				jQuery(slug).val('');
 				jQuery(description).val('');
				div.hide();
			  }
		});
	}
 	
 }
 var fgl_cancelAddCategory=function(obj){
 	div=jQuery("#apm_categ_layer");
 	div.hide();
 }
 
var fgl_submitComment=function(id,fieldname,post_id){
	commentBlock=jQuery("#"+id);
	commentTpl=jQuery("#"+fieldname+"_comment_tpl");
	lang=jQuery("#"+fieldname+"_lang option:selected").val() ;
	if(lang==undefined){
		lang='false';
	}
	var commentsList=jQuery("#"+fieldname+"_comments_list");
	var commentLoader=jQuery("#"+fieldname+"_comment_loader");
	var commentNb=jQuery("#"+fieldname+"_comment_nb");
	jQuery(commentLoader).show();
	txt=tinyMCE.activeEditor.getContent();//jQuery(commentBlock).attr("value");
	tinyMCE.activeEditor.setContent('');
	jQuery.ajax({
	  url: ajaxurl ,
 	 type: "POST",
 	 data: "lang="+lang+"&post_id="+post_id+"&comment="+txt+"&action=apm_save_comments&fieldname="+fieldname,
	  //context: document.body,
	  success: function(data){
		jQuery(commentLoader).hide();
		jQuery(commentsList).show();
		dataStr=String(data);
		dataStr=dataStr.substring(0,dataStr.length-1);
		dataStr=dataStr.split('***').join("'");
		jQuery(commentsList).append(dataStr);
		jQuery(commentBlock).attr("value",'');
		//jQuery(commentNb).empty();
		nb=Number(jQuery(commentNb).html())+1;
		jQuery(commentNb).html(nb);
		//_comment_nb
	  }
	});
	//alert(fieldname+"-"+commentTpl+"-"+jQuery(commentTpl).text());
	
	
};


var fgl_manageCategories=function(){//use all_categories
	    jQuery.each(all_categories, function(key, categ){  
	    	categdiv=jQuery("#"+key+"div");
	  	jQuery(categdiv).css('display','none');
	});
	
	//
}


var tabs_obj=[];
jQuery(document).ready(function(){
	
	 var winh=jQuery(window).height();
	 var winw=jQuery(window).width();
    tabs(tabs_obj);
    if(getCookie('ApmAdvSearch')==null){
    	setCookie('ApmAdvSearch','hidden',2);
    	var AdvSearch='hidden';
    } else {
    	var AdvSearch=getCookie('ApmAdvSearch');
    	
    }
      jQuery("#post").submit(function() {
	

		 jQuery.each(flg_comments_list, function(key, comment_block){  
		 	
			 txt=tinyMCE.get(comment_block.id).getContent()
		    	//alert(txt+'-');
		  	 jQuery("#"+comment_block.id).html(txt);
		});
	 	 return true;
	});
	
	//****AUTOSUGGEST MULTISELECT FUNCTIONS***///
	//
	
   jQuery(".multi_select_autosuggest_list > li > img").live('click', function(e){
		id=jQuery(this).attr('item_id');
		p=jQuery(this).parent().parent().parent();
		p=jQuery(p).find('.autocomplete_field_real_value');
		pval=jQuery(p[0]).attr('value');
		arrData=pval.split(',');
		li=jQuery(this).parent();
		jQuery(li[0]).hide();
		pos=jQuery.inArray(id, arrData);
		arrData.splice(pos,1);
		pval=arrData.join(',');
		jQuery(p[0]).attr('value',pval);
   });
	
   jQuery(".add_multi_select_autosuggest_list").live('click', function(e){
   	
		
		p=jQuery(this).parent().parent();
		fstr=jQuery(p).find('.autocomplete_field');
		fval=jQuery(p).find('.autocomplete_field_value');
		prealval=jQuery(p).find('.autocomplete_field_real_value');
		plist=jQuery(p).find('.multi_select_autosuggest_list');
		realval=jQuery(prealval[0]).attr('value');
		str=jQuery(fstr[0]).attr('value');
		val=jQuery(fval[0]).attr('value');
		if(realval!==''){
			arrData=realval.split(',');
		} else {
			arrData=[];
		}
   		if(val!==''){
	   		if(jQuery.inArray(val, arrData)!==-1){
	   			alert('This item is already in the list');
	   		} else  {
	   			arrData.push(val);
				pval=arrData.join(',');
				jQuery(prealval[0]).attr('value',pval);
				s='<li><a href="post.php?action=edit&post='+val+'" title="Click to open the related item edit form">'+str+' </a>';
				s+='<img src="'+apm_settings.paths.img+'block_16.png" title="Click to remove this item from the list" item_id="'+val+'"></li>';
	   	
				jQuery(plist).append(s);
			}
   		} else {
   			alert('Please, first you need to select an item in the auto suggest field above');
   		}
   });
	
	
	
	//******DATAGRID FUNCTIONS***///
	
	///CALL datagrid data ajax
	
	
	data_grids=jQuery(".apm_table_tbody");
	
	var apm_load_data_grid=function(data_grid,param_filter_key,param_filter_value){
		modulekey=jQuery(data_grid).attr('modulekey');
	 	shown=jQuery(data_grid).attr('shown');
	 	if(shown=='true'){
		 	var table=jQuery(data_grid);
	 		var grid=jQuery(data_grid).parents('.apm_grid_block_cls');
			var status_zone=grid.find('.apm_grid_status_zone');
			status_zone.html(' <span  class="apm_loader_img" ><img src="'+apm_settings.paths.css+'images/ui-anim_basic_16x16.gif" ></span><span class="apm_status_txt"><span class="apm_highlight">Status: </span>Loading records</span>');
				
			//filters=param_filters==undefined? false:param_filters;
			if(param_filter_key!==undefined && param_filter_key!==''){
				filters[param_filter_key]=param_filter_value;
			} 
			
			filters_str=jQuery.JSON.encode(filters);
			
	 		jQuery.ajax({
				  url: ajaxurl ,
			 	 type: "POST",
			 	 data: "modulekey="+modulekey+"&action=apm_manage_grid_data&todo=get_data&filters="+filters_str,
				  success: function(data){
					dataStr=String(data);
					dataStr=dataStr.substring(0,dataStr.length-1);
					dataCut=dataStr.split("//cutter//");
	 				table.append(dataCut[0])
	 				//alert(eval(dataCut[1]);
	 				rtrnObj=jQuery.parseJSON( dataCut[1]);
	 				
	 				if(rtrnObj.filters_results!==""){
	 					status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>Records loaded ('+rtrnObj.page_count+' / '+rtrnObj.total_count+'), filtered by: '+rtrnObj.filters_results+'</span>');
	 				}else {
	 					status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>Records loaded ('+rtrnObj.page_count+' / '+rtrnObj.total_count+')</span>');
	 				}
	 				
					gridwrap=jQuery(grid).parents(".apm_datagrid_wrapper");
					o=jQuery(gridwrap).find('.apm_grid_status_zone_container');
					obj=jQuery(o[0]).find('.apm_page_first');
					jQuery(o[0]).attr('last_page',rtrnObj.last_page);
					//apm_paging_page_nb=new_apm_paging_page_nb;
     					//apm_paging_old_page_nb
     					apm_paging_last_page=rtrnObj.last_page;
     					
					if(Number(jQuery(o[0]).attr('initial_page'))>Number(rtrnObj.last_page)){
						jQuery(o[0]).attr('initial_page',rtrnObj.last_page);
						do_change_paging(Number(rtrnObj.last_page),obj[0],true);
						//alert('oups');
					} else {
						do_change_paging(Number(jQuery(o[0]).attr('initial_page')),obj[0],true);
					}
					apm_paging_page_nb=Number(jQuery(o[0]).attr('initial_page'));
					apm_paging_old_page_nb=apm_paging_page_nb;
					//if()
				  }
			});
	 	}
	}
	 jQuery.each(data_grids, function(key, data_grid){  
	 	p=jQuery(data_grid).parents(".apm_datagrid_wrapper");
	 	sz=jQuery(p).find('.apm_grid_status_zone_container');
	 	has_paging=Number(jQuery(sz[0]).attr('has_paging'));
	 	if(has_paging==1){
	 		apm_load_data_grid(data_grid,'page_nb',1);
	 	} else {
	 		apm_load_data_grid(data_grid);
	 	}
	 });
   
   ///SET PAGING  
   
	var do_change_paging=function(page_nb,obj,norefresh){
		o=jQuery(obj).parents('.apm_pagin_header_zone');
		ochild=jQuery(o[0]).find('.apm_page_nb');
		oapm_page_first_child=jQuery(o[0]).find('.apm_page_first');
		oapm_page_prev_child=jQuery(o[0]).find('.apm_page_prev');
		oapm_page_next_child=jQuery(o[0]).find('.apm_page_next');
		oapm_page_last_child=jQuery(o[0]).find('.apm_page_last');
		if(page_nb==1){
			jQuery(oapm_page_first_child[0]).addClass('inactive');
			jQuery(oapm_page_prev_child[0]).addClass('inactive');
		} else {
			jQuery(oapm_page_first_child[0]).removeClass('inactive');
			jQuery(oapm_page_prev_child[0]).removeClass('inactive');
			
		}
		if(page_nb==get_last_page(obj)){
			jQuery(oapm_page_next_child[0]).addClass('inactive');
			jQuery(oapm_page_last_child[0]).addClass('inactive');
		} else {
			jQuery(oapm_page_next_child[0]).removeClass('inactive');
			jQuery(oapm_page_last_child[0]).removeClass('inactive');
		}
		jQuery(ochild[0]).attr('value',page_nb);
		
		gridwrap=jQuery(obj).parents(".apm_datagrid_wrapper");
		var grid=gridwrap.find('.apm_grid_block_cls');
		o=jQuery(obj).parents('.apm_grid_status_zone_container');
		jQuery(o[0]).attr('initial_page',page_nb);
		
		if(norefresh==undefined) {
			refresh_grid(grid,'page_nb',page_nb);
		}
	}
	var get_last_page=function(obj){
		o=jQuery(obj).parents('.apm_grid_status_zone_container');
		return Number(jQuery(o[0]).attr('last_page'));
	}
	
	////SEARCH
		
    jQuery(".apm_search_btn_go").live('click', function(){
    	f=jQuery(this).parent().find('.apm_search_field');
    	seaStr=jQuery(f).attr('value');
    	if(seaStr!==''){
	 	var gridparent=jQuery(this).parents('.apm_sidebar_block').parent();
	 	var grid=jQuery(gridparent).find('.apm_grid_block_cls');
	 	refresh_grid(grid,"free_search",seaStr);
    	}
 	//
    	
     });
     	
    jQuery(".apm_search_cancel_btn_go").live('click', function(){
    	f=jQuery(this).parent().find('.apm_search_field');
    	jQuery(f).attr('value','');
    	var gridparent=jQuery(this).parents('.apm_sidebar_block').parent();
 	var grid=jQuery(gridparent).find('.apm_grid_block_cls');
 	refresh_grid(grid,"free_search",'');
     });
         	
    jQuery(".apm_advanced_search_btn_go").live('click', function(){
    	f=jQuery(this).parents('.content_advanced_search_fields');
    	f=f[0];
    	fields=jQuery(f).find('select');
	 jQuery.each(fields,function(index, field) {
	 	v=jQuery(field).find('option:selected').text();
	 	n=jQuery(field).attr('name');
	 	if(v!=='Show All' && v!=='Show All '){
			filters[n]=v;
	 	}
	 });
	 
	 	
    	var gridparent=jQuery(this).parents('.apm_sidebar_block').parent();
 	var grid=jQuery(gridparent).find('.apm_grid_block_cls');
 	refresh_grid(grid,"",'');
    /*	
     * 
	  	var data_grid=grid.find('tbody');
		jQuery(data_grid).html("");
     * 
     * 
     jQuery(f).attr('value','');*/
    
     });
     
     
    jQuery(".apm_open_advanced_search").live('click', function(){
	    	var blockparent=jQuery(this).parents('.apm_sidebar_content_filter');
	    	var blockadvancedsearch=jQuery(blockparent).parent();
	    	jQuery(blockparent).hide();
	    	blockadvancedsearch=jQuery(blockadvancedsearch).find('.apm_sidebar_content_advanced_search')
	    	jQuery(blockadvancedsearch).show();
     });
	jQuery(".apm_close_advanced_search").live('click', function(){
	    	var blockparent=jQuery(this).parents('.apm_sidebar_content_advanced_search');
	    	var blockadvancedsearch=jQuery(blockparent).parent();
	    	jQuery(blockparent).hide();
	    	blockadvancedsearch=jQuery(blockadvancedsearch).find('.apm_sidebar_content_filter')
	    	jQuery(blockadvancedsearch).show();
     });
     
	///PAGING
	var apm_paging_old_page_nb=1;
	var apm_paging_page_nb=1;
	var apm_paging_last_page=10;
	
    jQuery(".apm_page_nb").live('focus', function(){
     	 apm_paging_old_page_nb=Number(jQuery(this).attr('value'));
     });
     
    jQuery(".apm_page_nb").live('blur', function(){
     	//alert('blur');
     	new_apm_paging_page_nb=Number(jQuery(this).attr('value'));
     	if(new_apm_paging_page_nb>0){
     		apm_paging_page_nb=new_apm_paging_page_nb;
     		apm_paging_old_page_nb=apm_paging_page_nb;
     		 do_change_paging(apm_paging_page_nb,this);
     	} else {
     		jQuery(this).attr('value',apm_paging_old_page_nb)
     	}
     });
   
   jQuery(".apm_page_nb").live('keypress', function(e){
   	if(e.which == 13){
     		jQuery(this).blur();
       }
   });
   jQuery(".apm_page_first").live('click', function(e){
     		apm_paging_page_nb=1;
		if(apm_paging_old_page_nb!==apm_paging_page_nb){
		 	do_change_paging(apm_paging_page_nb,this);
			apm_paging_old_page_nb=apm_paging_page_nb;
		}
   });
   jQuery(".apm_page_prev").live('click', function(e){
     		apm_paging_page_nb-=1;
     		if(apm_paging_page_nb==0){
     			apm_paging_page_nb=1;
     		}
		if(apm_paging_old_page_nb!==apm_paging_page_nb){
		 	do_change_paging(apm_paging_page_nb,this);
			apm_paging_old_page_nb=apm_paging_page_nb;
		}
   });
   jQuery(".apm_page_next").live('click', function(e){
   		apm_paging_last_page=get_last_page(this);
   		if(apm_paging_page_nb+1<=apm_paging_last_page){
     			apm_paging_page_nb+=1;
		if(apm_paging_old_page_nb!==apm_paging_page_nb){
		 	do_change_paging(apm_paging_page_nb,this);
			apm_paging_old_page_nb=apm_paging_page_nb;
		}
   	}
   });
   
   jQuery(".apm_page_last").live('click', function(e){
   		apm_paging_last_page=get_last_page(this);
		apm_paging_page_nb=apm_paging_last_page;
		if(apm_paging_old_page_nb!==apm_paging_page_nb){
		 	do_change_paging(apm_paging_page_nb,this);
			apm_paging_old_page_nb=apm_paging_page_nb;
		}
   });
   
	///SET A-Z filtering
	
    jQuery(".apm_grid_az_header > li > a").live('click', function(){
    		letter=jQuery(this).attr('letter');
	 	var grid=jQuery(this).parents('.apm_grid_block_cls');
	 	refresh_grid(grid,"letter",letter);
    		
    });
    
    var cb_clicked_store=[];
    
    
    
     jQuery(".apm_grid_row_cb").live('click', function(){
		post_id= jQuery(this).attr('post_id');
		var do_check=false;
	     	if(jQuery(this).attr('checked')=='checked'){
	     		do_check=true;
	     		pos=jQuery.inArray(post_id,cb_clicked_store);
	     		if(pos==-1){
	     			cb_clicked_store.push(post_id);
	     		}
	     	} else {
	     		do_check=false;
	     		pos=jQuery.inArray(post_id,cb_clicked_store);
	     		if(pos>-1){
	     			cb_clicked_store.splice(pos,1);
	     		} 
	     	}
		//alert(pos+"-"+post_id+"-"+do_check+"-"+cb_clicked_store);
     });
     
     
     jQuery(".apm_grid_head_cb").live('click', function(){
     	var do_check=false;
     	if(jQuery(this).attr('checked')=='checked'){
     		do_check=true;
     	}
	div=jQuery(this).parents('.apm_grid_block_cls');//.parent().parent().parent().parent().parent();//.parent().next();
	trs=div.find('table > tbody > tr');
 	cb_clicked_store=[];
	 jQuery.each(trs,function(index, tr) {
	 	tds=jQuery(tr).find('td');
	 	td=tds[0].firstChild;
 		post_id=jQuery(td).attr('post_id');
	 	if(do_check){
	 		jQuery(td).attr('checked','checked');
	 		cb_clicked_store.push(post_id);
	 	} else {
	 		jQuery(td).removeAttr('checked');
	 	}
	 });
     });
       	var refresh_grid=function(grid,param_filter_key,param_filter_value){
	  	var data_grid=grid.find('tbody');
		jQuery(data_grid).html("");
		apm_load_data_grid(data_grid,param_filter_key,param_filter_value);
	  }
	 jQuery(".apm_refresh_btn").on('click', function(){
		var grid=jQuery(this).parents('.apm_grid_block_cls');//.parent().parent().parent();
		refresh_grid(grid);
	  });
	
///SHOW LAYER ACTION ON  DATA GRIDS

	var countHideLayer=0;
	var apm_selected_post_id=0;
	var apm_selected_post_status=false;
	var apm_selected_post_object=false;   
	
	var apm_activateActionLayer=function(){
		countHideLayer=0;
	    jQuery(".apm_act_action").live('mouseover', function(){
		    	actionLayer=jQuery('#apm_grid_actions_layer');
		    	thisObj=jQuery(this);
		    	actionLayer.css("left",thisObj.position().left+20+"px").css("top",thisObj.position().top+"px");
			apm_selected_post_id=jQuery(this).attr('post_id');
			apm_selected_post_status=jQuery(this).attr('post_status');
		    	actionLayer.show();
		    	if(apm_selected_post_status=='publish'){
		    		actionLayer.find('.apm_act_pub').hide();
		    		actionLayer.find('.apm_act_unpub').show();
		    		actionLayer.find('.apm_act_trash').show();
		    	} else if(apm_selected_post_status=='pending' || apm_selected_post_status=='draft'){
		    		actionLayer.find('.apm_act_pub').show();
		    		actionLayer.find('.apm_act_unpub').hide();
		    		actionLayer.find('.apm_act_trash').show();
		    	}else if(apm_selected_post_status=='trash'){
		    		actionLayer.find('.apm_act_pub').show();
		    		actionLayer.find('.apm_act_unpub').show();
		    		actionLayer.find('.apm_act_trash').hide();
		    	}
			countHideLayer=0;
			apm_selected_post_object=this;
		});
		jQuery(".apm_act_action").live('mouseout', function(){
		    	apm_startCountHideLayer('#apm_grid_actions_layer');
		});
		 jQuery("#apm_grid_actions_layer > span").live('mouseout', function(){
		    	apm_startCountHideLayer('#apm_grid_actions_layer');
		})
		 jQuery("#apm_grid_actions_layer > span").live('mouseover', function(){
			countHideLayer=0;
		})
		
		    jQuery(".apm_act_edit").live('click', function(){
 			window.open('post.php?post='+apm_selected_post_id+'&action=edit','_blank');
		    });
		    
		        jQuery(".apm_act_trash").live('click', function(){
		        	if(jQuery(this).hasClass('apm_pad_icon')){
		        		apm_multi_update_status_ajax(this,'trash_multirecs','Trashing','Trashed');
		        	} else if(jQuery(this).hasClass('apm_filter_icon')){
		        		apm_filter_status_ajax(this,'filter_trash');
		        	}else {
					jQuery(apm_selected_post_object).parent().parent().hide();
					var grid=jQuery(apm_selected_post_object).parents('.apm_grid_block_cls');//.parent().parent().parent().parent().parent().parent();
					var status_zone=grid.find('.apm_grid_status_zone');
					var grid_tbody=grid.find('tbody');
					var modulekey=grid_tbody.attr('modulekey');
					status_zone.html(' <span  class="apm_loader_img" ><img src="'+apm_settings.paths.css+'images/ui-anim_basic_16x16.gif" ></span><span class="apm_status_txt"><span class="apm_highlight">Status: </span>trashing Record Id '+apm_selected_post_id+' </span>');
					jQuery.ajax({
						  url: ajaxurl ,
					 	 type: "POST",
					 	 data: "modulekey="+modulekey+"&action=apm_manage_grid_data&todo=trash_rec&post_id="+apm_selected_post_id,
						  success: function(data){
							status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>Record trashed</span>');
					
						  }//apm_get_grid_data
					});
		        		
		        	}
		        });
		        
		        jQuery(".apm_act_del").live('click', function(){
		        	if(cb_clicked_store.length==0 && jQuery(this).hasClass('apm_pad_icon')){
	    				alert("Please select at least one record");
	    				return;
	    			}
	    			
		        	if(jQuery(this).hasClass('apm_pad_icon')){
				    	var answer = confirm('Are you sure that you want to delete the Record(s) # '+cb_clicked_store.join(', ')+' ?');
					if (answer){
		        			apm_multi_update_status_ajax(this,'del_multirecs','Deleting','Deleted');
					}
		        	} else {
				    	var answer = confirm('Are you sure that you want to delete the Record ID '+apm_selected_post_id+' ?');
					if (answer){
						jQuery(apm_selected_post_object).parent().parent().hide();
						var grid=jQuery(apm_selected_post_object).parents('.apm_grid_block_cls');//.parent().parent().parent().parent().parent().parent();
						var status_zone=grid.find('.apm_grid_status_zone');
						var grid_tbody=grid.find('tbody');
						var modulekey=grid_tbody.attr('modulekey');
						status_zone.html(' <span  class="apm_loader_img" ><img src="'+apm_settings.paths.css+'images/ui-anim_basic_16x16.gif" ></span><span class="apm_status_txt"><span class="apm_highlight">Status: </span>deleting Record Id '+apm_selected_post_id+' </span>');
						jQuery.ajax({
							  url: ajaxurl ,
						 	 type: "POST",
						 	 data: "modulekey="+modulekey+"&action=apm_manage_grid_data&todo=del_rec&post_id="+apm_selected_post_id,
							  success: function(data){
								status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>Record Deleted</span>');
						
							  }//apm_get_grid_data
						});
					}
				}
		    });
		    var apm_filter_status_ajax=function(obj,status_action){
			gridwrap=jQuery(obj).parents(".apm_datagrid_wrapper");
			var grid=gridwrap.find('.apm_grid_block_cls');
			var status_zone=grid.find('.apm_grid_status_zone');	
			refresh_grid(grid,"post_status",status_action);
		    }
		    var apm_multi_update_status_ajax=function(obj,status_action,status_text1,status_text2){
		    			if(cb_clicked_store.length==0){
		    				alert("Please select at least one record");
		    				return;
		    			}
		    			p=jQuery(obj).parent();
		    			var status_action=status_action;
					modulekey=jQuery(p).attr('modulekey');
					gridwrap=jQuery(obj).parents(".apm_datagrid_wrapper");
					var grid=gridwrap.find('.apm_grid_block_cls');
					var status_zone=grid.find('.apm_grid_status_zone');
					html=' <span  class="apm_loader_img" ><img src="'+apm_settings.paths.css+'images/ui-anim_basic_16x16.gif" ></span>';
					html+='<span class="apm_status_txt"><span class="apm_highlight">Status: </span>'+status_text1+' the '+cb_clicked_store.length+' record(s) '+cb_clicked_store.join(', ')+' </span>';
					status_zone.html(html);
					jQuery.ajax({
						  url: ajaxurl ,
					 	 type: "POST",
					 	 data: "modulekey="+modulekey+"&action=apm_manage_grid_data&todo="+status_action+"&post_ids="+cb_clicked_store.join(','),
						  success: function(data){
							status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>'+cb_clicked_store.length+' Record(s) '+status_text2+'</span>');
							
							   switch(status_action){
							   	default:
									   jQuery.each(cb_clicked_store, function(key,id){  
									   	tr=jQuery('.'+modulekey+"_"+id);
									   	td_status=tr.find('.td_status');
									   	switch(status_action){
									   		case 'unpub_multirecs':
												jQuery(td_status[0]).removeClass('apm_act_pub');
												jQuery(td_status[0]).addClass('apm_act_unpub');
												jQuery(td_status[0]).addClass('apm_act_trash');
											break;
									   		case 'pub_multirecs':
												jQuery(td_status[0]).removeClass('apm_act_unpub');
												jQuery(td_status[0]).addClass('apm_act_pub');
												jQuery(td_status[0]).addClass('apm_act_trash');
											break;
									   		case 'trash_multirecs':
												jQuery(td_status[0]).addClass('apm_act_unpub');
												jQuery(td_status[0]).addClass('apm_act_pub');
												jQuery(td_status[0]).removeClass('apm_act_trash');
											break;
									   	}
									   });
									   if(status_action=="trash_multirecs"){
									   	refresh_grid(grid);
						   				cb_clicked_store=[];
									   }
								break;
						   		/*case 'trash_multirecs':
						   			
								break;*/
						   		case 'del_multirecs':
						   			refresh_grid(grid);
						   			cb_clicked_store=[];
								break;
							}	
							//refresh_grid(grid);
						  }
					});
		    	
		    }
		    var apm_update_status_ajax=function(status_action,status_text1,status_text2){
		    		var grid=jQuery(apm_selected_post_object).parents('.apm_grid_block_cls');
				apm_act_action=jQuery(apm_selected_post_object).parent().parent().find('.apm_act_action');
				jQuery(apm_act_action).attr('post_status','draft')
				td_status=jQuery(apm_selected_post_object).parent().parent().find('.td_status');
				if(status_action=='unpub_rec'){
					jQuery(td_status).removeClass('apm_act_pub');
					jQuery(td_status).addClass('apm_act_unpub');
					jQuery(td_status).addClass('apm_act_trash');
				} else if(status_action=='pub_rec'){
					jQuery(td_status).removeClass('apm_act_unpub');
					jQuery(td_status).addClass('apm_act_pub');
					jQuery(td_status).addClass('apm_act_trash');
				} else if(status_action=='trash_multirecs'){
					jQuery(td_status).addClass('apm_act_unpub');
					jQuery(td_status).addClass('apm_act_pub');
					jQuery(td_status).removeClass('apm_act_trash');
				}
				var status_zone=grid.find('.apm_grid_status_zone');
				var grid_tbody=grid.find('tbody');
				var modulekey=grid_tbody.attr('modulekey');
				html='<span  class="apm_loader_img" ><img src="'+apm_settings.paths.css+'images/ui-anim_basic_16x16.gif" ></span>';
				html+='<span class="apm_status_txt"><span class="apm_highlight">Status: </span>'+status_text1+' Record Id '+apm_selected_post_id+' </span>';
				status_zone.html(html);
				jQuery.ajax({
					  url: ajaxurl ,
				 	 type: "POST",
				 	 data: "modulekey="+modulekey+"&action=apm_manage_grid_data&todo="+status_action+"&post_id="+apm_selected_post_id,
					  success: function(data){
						status_zone.html('<span class="apm_status_txt"><span class="apm_highlight">Status: </span>Record '+status_text2+'</span>');
					  }
				});
		    }
		        jQuery(".apm_act_all").live('click', function(){
		        	if(jQuery(this).hasClass('apm_filter_icon')){
		        		apm_filter_status_ajax(this,'filter_all');
		        	}
		    });
		        jQuery(".apm_act_unpub").live('click', function(){
		        	if(jQuery(this).hasClass('apm_pad_icon')){
		        		apm_multi_update_status_ajax(this,'unpub_multirecs','Unpublishing','Unpublished');
		        		
		        	}  else if(jQuery(this).hasClass('apm_filter_icon')){
		        		apm_filter_status_ajax(this,'filter_unpub');
		        	} else {
		        		apm_update_status_ajax('unpub_rec','Unpublishing','Unpublished');
				}
		    });
		    
		        jQuery(".apm_act_pub").live('click', function(){
		        	if(jQuery(this).hasClass('apm_pad_icon')){
		        		apm_multi_update_status_ajax(this,'pub_multirecs','Publishing','Published');
		        	} else if(jQuery(this).hasClass('apm_filter_icon')){
		        		apm_filter_status_ajax(this,'filter_pub');
		        	} else {
		        		apm_update_status_ajax('pub_rec','Publishing','Published');
				}
		    });
		        jQuery(".apm_act_view").live('click', function(){
		    	//alert('view '+apm_selected_post_id);
		    });
	}
	apm_activateActionLayer();
	 				
	var apm_startCountHideLayer=function(obj_id){
       		 var date = new Date();
		countHideLayer=date.getTime();
		setTimeout(apm_CheckHideLayer,500,obj_id);
	}
	var apm_CheckHideLayer=function(obj_id){
		//alert(countHideLayer);
		if(countHideLayer!==0){
	    		actionLayer=jQuery(obj_id);
	    		actionLayer.hide();
			apm_selected_post_id=0;
			apm_selected_post_object=false;
		}
		countHideLayer=0;
	}
	
/////HANDLE Show the help layer on rollover on a ? icon
    jQuery(".apm_help_btn").live('mouseover', function(){
    	//alert(jQuery(this).next());
    //	alert(jQuery(this).next().text());
    	helpTxt=jQuery(this).next().text();
    	helpObject=jQuery(this).next();
    	helpObject.css("left",jQuery(this).position().left+30+"px").css("top",jQuery(this).position().top+"px");
    	helpObject.show();
   }); 
    jQuery(".apm_help_btn").live('mouseout', function(){
    		helpObject=jQuery(this).next();
    		helpObject.hide();
   }); 
    //END
    
	jQuery('.fileRemove').live('click',function(){
			jQuery(this).parent().hide();
			jQuery(this).next().val(jQuery(this).attr('fileid'));
			fieldname=jQuery(this).attr('fieldname');
			filednb=jQuery(this).attr('fieldnb');
			filetype=jQuery(this).attr('filetype');
			if(filetype=="main"){
				jQuery("#"+fieldname).show();
			}
	});
	//
	jQuery('.fileAddDescription_btn').live('click',function(){
		jQuery(this).next().next().show();
		jQuery(this).next().next().css('display','block');
	});
	jQuery('.fileHelpLayer_btn').live('click',function(){
		
	});
	
	//
	
	jQuery('.apm_add_upload').live('click',function(){
			if(this.nbupload==undefined){
				this.nbupload=0;
			}
			this.nbupload+=1;
			fieldname=jQuery(this).attr('fieldname');
			uploadfield=jQuery("#"+fieldname);
			uploadfieldcount=jQuery("#"+fieldname+"_add_file");
			jQuery(uploadfieldcount).val(this.nbupload);
			//<div><input style="'.$upload_field_display.'" type="file" id="'.$config['field'].'" name="'.$config['field'].'_value" value="'.$config['value'].'" '.$config['width'].' /></div>
			uploadfieldnew=jQuery(this).parent().parent().append('<div><input  type="file" id="'+fieldname+'_'+this.nbupload+'" name="'+fieldname+'_value_'+this.nbupload+'" value="" /></div>');
			
			uploadfieldnew.css('display','block');
	});
	
 	/* a = jQuery('.autocomplete_field').autocomplete( { 
 	 	serviceUrl:ajaxurl+"?callback=?&action=amp-ajax-autocomplete&fieldname="+jQuery(this).attr(),
    		minChars:2 
    	});*/


                    jQuery.each(jQuery('.autocomplete_field'), function(i, obj){  
	                    var fieldname=jQuery(obj).attr('fieldname');
	                    var post_type=jQuery(obj).attr('post_type');
	                    a= jQuery(obj).autocomplete( { 
			 	 	serviceUrl:ajaxurl+"?callback=?&action=amp-ajax-autocomplete&fieldname="+fieldname+"&post_type="+post_type,
			    		minChars:2 
			    	});
			    	 jQuery(obj).blur(function(){
			    	 	if(jQuery(this).val()==''){
      						jQuery(this).next().val('');
			    	 	}
			    	 });
	               });  
	               

			jQuery('.apm_is_required').live('blur',function(i, obj){  
	                	if(jQuery(this).val()==''){
	                		//alert('This field is required, please input a value');
	                		jQuery(this).parent().parent().addClass('apm_invalid');
	                		jQuery(this).focus()
	                	} else {
	                		jQuery(this).parent().parent().removeClass('apm_invalid');
		                }
	                });	
	                jQuery('.apm_is_email').live('blur',function(i, obj){  
	                	 var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 				  var address = jQuery(this).val();
  				 if(reg.test(address) == false && address!=='') {
	                		jQuery(this).parent().parent().addClass('apm_invalid');
	                		jQuery(this).focus()
		                } else {
	                		jQuery(this).parent().parent().removeClass('apm_invalid');
		                }
	                });	
	                jQuery('.apm_is_numbers').live('blur',function(i, obj){  
	                
 				  var num = jQuery(this).val();
 				 
				if ( isNaN(num)) {
					jQuery(this).parent().parent().addClass('apm_invalid');
	                		jQuery(this).focus()
		                } else {
	                		jQuery(this).parent().parent().removeClass('apm_invalid');
		                }
	                	
	                });	
	                jQuery('.apm_is_phone').live('blur',function(i, obj){  
	                	
	                	
		               error='';
 				  var phone = jQuery(this).val();
		               var stripped = phone.replace(/[\(\)\.\-\+\ ]/g, '');    
 				  
				 if (isNaN(stripped)) {
				        error = "The phone number contains illegal characters.\n";
					jQuery(this).parent().parent().addClass('apm_invalid');
				    } else if (stripped.length <8 && stripped.length >0 ) {
				        error = "The phone number is the wrong length. Make sure you included an area code.\n";
					jQuery(this).parent().parent().addClass('apm_invalid');
				    } else {
	                		jQuery(this).parent().parent().removeClass('apm_invalid');
		                }
	                	
	                });
			//apm_is_required
	
	
	
	jQuery('.apm_imgfile > img').live('click',function(){
			
			str_height=' height="500" ';
			if(jQuery(this).attr('has_resize')=='true'){
				str_height='';
			}
			jQuery('body').prepend('<div id="img_zoom_block" class="apm_imgfile_zoom"><h3 class="apm_win_header">Zoom</h3><div><img src="'+jQuery(this).attr('file_zoom')+'" '+str_height+' /></div></div>');
			zoom_block=jQuery('#img_zoom_block');
			img_zoom_block=jQuery('#img_zoom_block > img');
			w=zoom_block.width();
			h=zoom_block.height();
			wi=img_zoom_block.width();
			if(wi>w){
				nh=img_zoom_block.height()*((w-10)/wi);
				img_zoom_block.css('width',(w-10)+"px");
				img_zoom_block.css('height',nh+"px");
			}
			zoom_block.css('left',((jQuery(window).width()-w)/2)+"px");
			s=jQuery(window).scrollTop() ;
			winh=jQuery(window).height();
			zoom_block.css('top',((winh-h)/2+s)+"px");
			zoom_block.live('click',function(){
				jQuery(this).remove();
			});
	
	});
	//apm_imgfile
    //var AdvSearch='hidden';
    jQuery(function(){
			//jQuery.localise('ui-multiselect', {/*language: 'en',*/ path: 'js/locale/'});
			jQuery(".multiselect").multiselect();
			//jQuery('#switcher').themeswitcher();
		});
	
	if(AdvSearch=='shown'){
		jQuery("#apm_searchBlock_fields").show();
		jQuery("#apm_searchBlock_Hide").text('(Hide)');
	} else {
		jQuery("#apm_searchBlock_fields").hide();
		jQuery("#apm_searchBlock_Hide").text('(Show)');
	}
	jQuery("#apm_searchBlock_Hide").live('click', function(){
		if(AdvSearch=='shown'){
			jQuery("#apm_searchBlock_fields").hide();
    			 AdvSearch='hidden';
    			setCookie('ApmAdvSearch',AdvSearch,2);
			this.firstChild.nodeValue ='(Show)';
		} else {
			jQuery("#apm_searchBlock_fields").show();
    			 AdvSearch='shown';
    			setCookie('ApmAdvSearch',AdvSearch,2);
			this.firstChild.nodeValue ='(Hide)';
		}
	});
	
	if(all_categories!==false){
		attrdiv=jQuery("#pageparentdiv");
		attributesInside=jQuery("#pageparentdiv > div.inside");
		attributesInsideH=attributesInside.html();
		//alert(attributesInside);
		//pageparentdiv
		attrdiv.empty();
		var accordions='<div id="accordion">';
		if(apm_show_attributes){
			accordions+='<h4><a href="#">Attributes</a></h4>';
			accordions+='<div>'+attributesInsideH+'</div>';
		}
		 jQuery.each(all_categories, function(key, categ){  
		    	categdiv=jQuery("#"+key+"-all");
		    	//categdivadder=jQuery("#"+key+"-adder");
		    	if(categdiv!==undefined){
			    	categdivH=categdiv.html();
			    	//categdivadderH=categdivadder.html();
			    	accordions+='<h4><a href="#">'+categ.name+'</a></h4>';
			    	accordions+='<div ><div  class="apm_categ_block">'+categdivH+'</div>';
				accordions+='<div ><a href="edit-tags.php?taxonomy='+key+'" target="_blank">Manage category</a> ';
				accordions+='<img src="'+apm_settings.paths.img+'/plus_16.png" onclick="apm_show_categ_add(this); " style="cursor:pointer;" title="Quick add a category" category_name="'+key+'"></div>';
			    	accordions+='</div>';
				
			}
		});
		/**/
		accordions+='</div>';
		
		attrdiv.append('<div class="handlediv" title="Click to toggle"><br /></div><h3 class="hndle"><span>Attributes and Categories</span></h3>'+accordions+' ');
		formCateg='<div  id="apm_categ_layer">';//display:none; 
	    	formCateg+='<h3>Add a category</h3><input name="tag-categ"  id="tag-categ" value="" type="hidden"><ul>';
	    	formCateg+='<li><label for="tag-name">Name*:</label><input name="tag-name"  id="tag-name" value="" size="50" type="text"><p id="apm_categ_layer_alert">Field required.</p></li>';
	    	formCateg+='<li><label for="tag-slug">Slug:</label><input name="tag-slug"  id="tag-slug" value="" size="50" type="text"></li>';
	    	formCateg+='<li><label for="tag-description">Description:</label><br/><textarea name="tag-description" id="tag-description" rows="5" cols="68"></textarea></li>';
	    	formCateg+='<li id="apm_categ_layer_button"><input  name="category_value_submit" value="Add new category" onclick="fgl_addCategory();" type="button" ><input   value="Cancel" onclick="fgl_cancelAddCategory();" type="button" ></li>';
	    	formCateg+='</ul><div  id="apm_categ_layer_sending"><img src="'+apm_settings.paths.css+'/images/ui-anim_basic_16x16.gif"/> Senging....</div></div>';
	    	
	    	
		bodydiv=jQuery("body");
		bodydiv.append(formCateg);
		jQuery( "#accordion" ).accordion();
		 jQuery.each(all_categories, function(key, categ){  
		    	categdiv=jQuery("#"+key+"div");
		  	jQuery(categdiv).remove();
		});
	}
});